package com.mgq.juc.cas;

import sun.misc.Unsafe;

/**
 * 模拟实现自己的原子类
 */
public class MyAtomicInteger {
    /**
     * 用来被保护的对象
     */
    private volatile int value;
    private static final Unsafe UNSAFE;
    private static final Long valueOffset;

    static {
        try {
            UNSAFE = UnsafeAccessor.getUnsafe();
            valueOffset = UNSAFE.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            //检查异常,转为运行时异常,抛出
            throw new RuntimeException(e);
        }
    }

    public int getValue() {
        return value;
    }

    /**
     * 自己利用CAS来实现的decrement方法
     *
     * @param amount 需要减的数
     */
    public void decrement(int amount) {
        while (true) {
            int prev = this.value;
            int next = prev - amount;
            if (UNSAFE.compareAndSwapInt(this, valueOffset, prev, next)) {
                break;
            }
        }
    }

}
